//
//  StatusListViewModel.swift
//  wbxm
//
//  Created by apple on 15/12/21.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class StatusListViewModel: NSObject {

//    since_id 是实现下拉刷新 新的微博的字段
    class func loadHomePageData(since_id: Int64, max_id:Int64 ,finished: (statuses: [Status]?) -> ()) {
        //实现网络请求

        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //判断token是否为空
        guard let token = UserAccountMode().token else{
            print("token为空")
            
            SVProgressHUD.showInfoWithStatus("请重新输入")
            finished(statuses: nil)
            return
        }
        
        var parameters = ["access_token" : token]

        
        if since_id > 0 {
            
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlStr, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                //失败
                print(error)
                SVProgressHUD.showInfoWithStatus("网络加载错误，请稍候再试")
                //执行失败的回调的
                finished(statuses: nil)
                return
            }
            
            //成功
            if let array = dict!["statuses"] as? [[String : AnyObject]] {
                //TODO: 遍历数组中 所有的字典 做字典转模型的操作
                //                    print(array)
                var list = [Status]()
                for item in array {
                    let s = Status(dict: item)
                    list.append(s)
                }
                
                finished(statuses: list)

                
            }
            
        }
//        SVProgressHUD.dismiss()
    }

}

